import {AsyncStorage,Platform} from 'react-native';
import Config from './config'
let Api = {};
function Http(isDebug = Config.isDebug,timeout = 20000){
    this.isDebug = isDebug;
    this.timeout = timeout;
};
Http.prototype = {
  ROOT_URL:Config.url,

  getAccessToken(){
        return AsyncStorage.getItem(Config.accessToken);
  },

  post2(key,body = {}, header = {}) {
        header = Object.assign({
              'Content-Type': 'multipart/form-data;',
        }, header);
        return this._send(key,"POST", body, header, true);
  },

  post(key,body = {}, header = {}){
    return this._send(key,"POST", body, header);
  },

  get(key,body = {}, header = {}){
    return this._send(key,"GET", body, header);
  },

  _send(key,method, body, header, dataIsFormData = false) {
    const sendUrl = this.ROOT_URL+Api[key];
    let mBody = body;
    var promise = new Promise((resolve, reject) =>{
        this._getAccestoken()
        .then((token)=>{
            let fd = null;
            if (dataIsFormData) {
                    fd = mBody;
                    fd.append("access_token", token||"");
                    fd.append("_device", Platform.OS);
                    fd.append("app_key","test");
                    fd.append("app_secret","testtest");
            } else {
                    fd = this._getFromData(Object.assign({
                        "access_token":token||"",
                        "_device":Platform.OS,
                        "app_key":"test",
                        "app_secret":"testtest"
                    }, mBody));
            }
            let headers = Object.assign({// "Content-Type":"application/json;charset=utf-8",
                "Accept": "application/json;"}, header);
            let body = {
                    method: method,
                    headers: headers,
                    body: fd
            };
            console.log(body,sendUrl);
            fetch(sendUrl, body)
            .then((res) => res.text()).then((rtext) => {
                var rdate = {};
                try {
                    rdate = JSON.parse(rtext);
                    if (rdate.debug) {
                            alert(rtext);
                    }
                    this._checkAccessToken(rdate.access_token);
                    console.log(body)
                    // if(this.isDebug){
                    //     console.group('--------net-pull--------');
                    //     console.log(sendUrl);
                    //     console.log(body)
                    //     console.log(rdate)
                    //     console.groupEnd();
                    // }
                    resolve(rdate);
                } catch (e) {
                    reject({msg:rtext})
                }
            }).catch((e) => {
                console.log(e);
                // if(this.isDebug){
                //     console.group('--------net-error--------');
                //     console.log(sendUrl);
                //     console.log(body)
                //     console.log(e)
                //     console.groupEnd();
                // }
                reject({msg:"network error!"})
            });
        })
    });
    return Promise.race([
        promise,
        new Promise((resolve,reject)=>{
            setTimeout(()=> reject(new Error('request timeout')),this.timeout)
    })])
  },

  _getFromData(o){
    var fd = new FormData();
    for(var k in o){
        let v = o[k];
        fd.append(k,v);
    }
    return fd;
  },

  _checkAccessToken(token){
    this._getAccestoken()
    .then(otoken=>{
            if(otoken != token){
                AsyncStorage.setItem("access_token",token);
            }
    })
  },
  _getAccestoken(){
    return new Promise((resolve,reject)=>{
            if(global.access_token){
                resolve(global.access_token)
            }else{
                AsyncStorage.getItem("access_token",(err,token)=>{
                        resolve(token);
                })
            }
    })
  }
}

export default Http;
export const addApi = function(apis){
    if(typeof apis == 'object' && !Array.isArray(apis)){
        Object.assign(Api,apis);
    }else{
        throw new Error("请加入一个key-value形式的api列表！");
    }
}